// pages/bill/bill.js
const app = getApp()
const db = wx.cloud.database()
Page({

  data: {
    openid: '',
    show: false,
    date: '',
    datalist: [],
    datlist: [],
    expenditure: 0,
    income: 0,
    loading: true,
    datlist_id: 0,
    minDate: new Date().getTime() - 864000000,
    defaultdate: new Date().getTime(),
    maxDate: new Date().getTime(),
    income_id: 0,
    sheetshow: false,
    actions: [
      {
        name: '删除',
      }
    ],
    del_id: '',
    isGuest: false,
    showGuestTip: false,
    refreshing: false,
    activeTab: 0, // 当前激活的标签页索引：0-全部，1-收入，2-支出
    incomeList: [], // 收入记录列表
    expenditureList: [] // 支出记录列表
  },

  onShow: function (options) {
    // 更新自定义tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    
    // 检查登录状态
    const userId = wx.getStorageSync('id')
    if (!userId) {
      // 未登录，跳转到登录页
      wx.redirectTo({
        url: '../login/login'
      })
      return
    }

    // 检查游客模式
    const isGuest = wx.getStorageSync('isGuest') || false
    this.setData({
      isGuest: isGuest,
      showGuestTip: isGuest
    })
    
    // 更新全局游客状态
    app.globalData.isGuest = isGuest
    
    // 检查数据更新标志，如果有新数据则刷新
    const dataUpdated = wx.getStorageSync('dataUpdated')
    if (dataUpdated) {
      // 清除更新标志
      wx.removeStorageSync('dataUpdated')
      console.log('检测到数据更新，正在刷新...')
    }
    
    this.getdata()
  },
  getdata() {
    let that = this
    console.log('当前用户ID:', wx.getStorageSync('id'));
    that.setData({ openid: wx.getStorageSync('id'), date: '', loading: true, income_id: 0 });
    
    // 检查是否为游客模式
    const isGuest = wx.getStorageSync('isGuest')
    
    if (isGuest) {
      // 游客模式：从本地存储读取数据
      try {
        const localRecords = wx.getStorageSync('guestRecords') || []
        console.log('游客模式本地数据:', localRecords);
        that.processData(localRecords)
      } catch (e) {
        console.error('读取游客数据失败：', e)
        that.setData({ loading: false });
        wx.showToast({
          title: '读取数据失败',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      // 正常用户：从云数据库读取数据
      wx.cloud.callFunction({
        name: 'getlist',
        success: function (res) {
          console.log('云函数返回数据:', res);
          if (!res.result.success) {
            console.error('获取数据失败:', res.result);
            wx.showToast({
              title: '获取数据失败',
              icon: 'none',
              duration: 2000
            })
            that.setData({ loading: false });
            return;
          }
          const result = res.result.data || [];
          that.processData(result)
        },
        fail: function(error) {
          console.error('调用云函数失败：', error)
          wx.showToast({
            title: '获取数据失败',
            icon: 'none',
            duration: 2000
          })
          that.setData({ loading: false });
        }
      })
    }
  },
  
  // 处理数据的通用方法
  processData(result) {
    let that = this
    // 获取全部数据
    that.setData({
      datalist: result.filter(e => { return e.date.slice(0, 7) == that.formatDatenouth(new Date()) }).sort(function (a, b) {
        return Date.parse(a.date) - Date.parse(b.date);
      }).filter(e => { return e.userid == wx.getStorageSync('id') })
    });
    // 数据整合.
    let ceshi = result.filter(e => { return e.date.slice(0, 7) == that.formatDatenouth(new Date()) }).sort(function (a, b) {
      return Date.parse(a.date) - Date.parse(b.date);
    }).filter(e => { return e.userid == wx.getStorageSync('id') })
    // 收入和支出费用计算
    let expenditure = 0
    let income = 0
    ceshi.filter(e => { return e.money < 0 }).forEach(e => {
      expenditure = expenditure + e.money
    })
    ceshi.filter(e => { return e.money > 0 }).forEach(e => {
      income = income + e.money
    })
    that.setData({ expenditure: expenditure, income: income });
    console.log('支出' + expenditure, '收入' + income)
    // 数据根据日期分类
    let ceshidata = []
    ceshi.forEach(e => {
      ceshidata.push(e.date)
    })
    let datlist = []
    let incomeList = []
    let expenditureList = []
    
    // 处理日期分类数据
    for (var i = 0; i < Array.from(new Set(ceshidata)).length; i++) {
      let currentDate = Array.from(new Set(ceshidata))[i];
      let ceshidatas = ceshi.filter(e => { return e.date == currentDate })
      let expenditure = 0;
      let income = 0;
      
      // 计算当日收入支出
      ceshidatas.filter(e => { return e.money < 0 }).forEach(e => {
        expenditure = expenditure + e.money
      })
      ceshidatas.filter(e => { return e.money > 0 }).forEach(e => {
        income = income + e.money
      })
      
      // 全部记录
      datlist.push({ 
        date: currentDate, 
        data: ceshidatas, 
        expenditure: expenditure, 
        income: income 
      })
      
      // 收入记录
      let incomeData = ceshidatas.filter(e => { return e.money > 0 })
      if (incomeData.length > 0) {
        incomeList.push({
          date: currentDate,
          data: incomeData,
          income: income
        })
      }
      
      // 支出记录
      let expenditureData = ceshidatas.filter(e => { return e.money < 0 })
      if (expenditureData.length > 0) {
        expenditureList.push({
          date: currentDate,
          data: expenditureData,
          expenditure: expenditure
        })
      }
    }
    
    that.setData({ 
      datlist: datlist, 
      incomeList: incomeList,
      expenditureList: expenditureList,
      loading: false, 
      datlist_id: 1, 
      income_id: 1 
    });
  },
  onDisplay() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },
  formatDate(date) {
    const dt = new Date(date);
    const y = dt.getFullYear();
    const m = (dt.getMonth() + 1 + "").padStart(2, "0");
    const d = (dt.getDate() + "").padStart(2, "0");
    return `${y}-${m}-${d}`;
  },
  formatDatenouth(date) {
    const dt = new Date(date);
    const y = dt.getFullYear();
    const m = (dt.getMonth() + 1 + "").padStart(2, "0");
    return `${y}-${m}`;
  },
  onConfirm(event) {
    this.setData({
      show: false,
      date: this.formatDate(event.detail),
      loading: true,
      datlist_id: 0,
      income_id: 0
    });
    let that = this
    
    // 检查是否为游客模式
    const isGuest = wx.getStorageSync('isGuest')
    
    if (isGuest) {
      // 游客模式：从本地存储读取数据并筛选日期
      try {
        const localRecords = wx.getStorageSync('guestRecords') || []
        const filteredRecords = localRecords.filter(e => { 
          return e.date == that.data.date && e.userid == wx.getStorageSync('id') 
        })
        that.processFilteredData(filteredRecords)
      } catch (e) {
        console.error('读取游客数据失败：', e)
        that.setData({ loading: false });
        wx.showToast({
          title: '读取数据失败',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      // 正常用户：从云数据库读取数据
      wx.cloud.callFunction({
        name: 'getlist',
        success: function (res) {
          if (!res.result.success) {
            console.error('获取数据失败:', res.result);
            wx.showToast({
              title: '获取数据失败',
              icon: 'none',
              duration: 2000
            })
            that.setData({ loading: false });
            return;
          }
          
          // 获取全部数据并筛选日期
          const result = res.result.data || [];
          const filteredRecords = result.filter(e => { 
            return e.date == that.data.date && e.userid == wx.getStorageSync('id') 
          })
          that.processFilteredData(filteredRecords)
        }, 
        fail: function(error) {
          console.error('调用云函数失败：', error)
          wx.showToast({
            title: '获取数据失败',
            icon: 'none',
            duration: 2000
          })
          that.setData({ loading: false });
        }
      })
    }
  },
  
  // 处理筛选后的数据
  processFilteredData(filteredRecords) {
    let that = this
    
    // 设置筛选后的数据列表
    that.setData({ 
      datalist: filteredRecords 
    });
    
    // 收入和支出费用计算
    let expenditure = 0
    let income = 0
    filteredRecords.filter(e => { return e.money < 0 }).forEach(e => {
      expenditure = expenditure + e.money
    })
    filteredRecords.filter(e => { return e.money > 0 }).forEach(e => {
      income = income + e.money
    })
    that.setData({ expenditure: expenditure, income: income });
    console.log('支出' + expenditure, '收入' + income)
    
    // 数据根据日期分类
    let ceshidata = []
    filteredRecords.forEach(e => {
      ceshidata.push(e.date)
    })
    
    let datlist = []
    let incomeList = []
    let expenditureList = []
    
    // 处理日期分类数据
    for (var i = 0; i < Array.from(new Set(ceshidata)).length; i++) {
      let currentDate = Array.from(new Set(ceshidata))[i];
      let ceshidatas = filteredRecords.filter(e => { return e.date == currentDate })
      let expenditure = 0;
      let income = 0;
      
      // 计算当日收入支出
      ceshidatas.filter(e => { return e.money < 0 }).forEach(e => {
        expenditure = expenditure + e.money
      })
      ceshidatas.filter(e => { return e.money > 0 }).forEach(e => {
        income = income + e.money
      })
      
      // 全部记录
      datlist.push({ 
        date: currentDate, 
        data: ceshidatas, 
        expenditure: expenditure, 
        income: income 
      })
      
      // 收入记录
      let incomeData = ceshidatas.filter(e => { return e.money > 0 })
      if (incomeData.length > 0) {
        incomeList.push({
          date: currentDate,
          data: incomeData,
          income: income
        })
      }
      
      // 支出记录
      let expenditureData = ceshidatas.filter(e => { return e.money < 0 })
      if (expenditureData.length > 0) {
        expenditureList.push({
          date: currentDate,
          data: expenditureData,
          expenditure: expenditure
        })
      }
    }
    
    that.setData({ 
      datlist: datlist, 
      incomeList: incomeList,
      expenditureList: expenditureList,
      loading: false, 
      datlist_id: 1, 
      income_id: 1 
    });
  },
  deldata(event) {
    console.log(event)
    this.setData({ sheetshow: true, del_id: event.target.dataset.item._id });
  },
  onClose() {
    this.setData({ sheetshow: false });
  },
  onSelect(event) {
    let that = this
    console.log(event.detail);
    // 删除逻辑
    db.collection('record').doc(this.data.del_id).remove({
      success: res => {
        wx.showToast({
          title: '删除成功',
        })
        that.getdata()
      }, fail: err => {
        wx.showToast({
          icon: 'none',
          title: '删除失败',
        })
      }
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    console.log('下拉刷新触发')
    this.setData({ refreshing: true })
    this.getdata()
    // 停止下拉刷新动画
    setTimeout(() => {
      wx.stopPullDownRefresh()
      this.setData({ refreshing: false })
    }, 1000)
  },

  // 上拉加载更多（预留接口）
  onReachBottom() {
    console.log('触底加载更多')
    // 这里可以实现分页加载逻辑
  },

  // 手动刷新数据
  refreshData() {
    console.log('手动刷新数据')
    this.setData({ loading: true })
    this.getdata()
  },
  
  // 切换标签页
  switchTab(event) {
    const index = parseInt(event.currentTarget.dataset.index);
    this.setData({
      activeTab: index
    });
  },
  
  // 滑动切换
  swiperChange(event) {
    const index = event.detail.current;
    this.setData({
      activeTab: index
    });
  }
})